﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.CRUDSqlAzure.Phone.Converters
{
    using System;
    using System.Windows.Data;
    using System.IO;
    using System.Windows.Media.Imaging;
    using System.Windows;
    using Microsoft.Phone;


    public class ImageConverter : IValueConverter
    {
        /// <summary>
        /// Converts a Jpeg byte array into a WriteableBitmap
        /// </summary>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is byte[])
            {
                MemoryStream stream = new MemoryStream((Byte[])value);
                WriteableBitmap bmp = PictureDecoder.DecodeJpeg(stream);
                return bmp;
            }
            else
                return null;
        }
        /// <summary>
        /// Converts a WriteableBitmap into a Jpeg byte array.
        /// </summary>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            WriteableBitmap bmp = (WriteableBitmap)value;
            int[] p = bmp.Pixels;
            int len = p.Length * 4;
            byte[] result = new byte[len]; // ARGB
            Buffer.BlockCopy(p, 0, result, 0, len);
            return result;
        }
    }
}